package todo;

import done.AbstractWashingMachine;
import se.lth.cs.realtime.*;

public class SpinController extends PeriodicThread {
	private boolean spinn;
	private AbstractWashingMachine theMachine;
	private int mode;
	private int timer;
	private int spinPeriod;

	public SpinController(AbstractWashingMachine theMachine, long speed) {
		super(speed);
		spinn = true;
		this.theMachine = theMachine;
		mode = 0;
		timer = 0;
		spinPeriod = 60;
	}

	public void perform() {
		SpinEvent e = (SpinEvent) mailbox.tryFetch();
		if (e != null) {
			mode = e.getMode();
			e = null;
		}

		if (mode == SpinEvent.SPIN_OFF) {
			theMachine.setSpin(SpinEvent.SPIN_OFF);
		} else if (mode == SpinEvent.SPIN_SLOW) {
			timer++;

			if (timer == spinPeriod) {
				spinn = !spinn;
				timer = 0;
			}
			if (spinn) {
				theMachine.setSpin(theMachine.SPIN_LEFT);
			} else {
				theMachine.setSpin(theMachine.SPIN_RIGHT);
			}

		} else if (mode == SpinEvent.SPIN_FAST) {
			theMachine.setSpin(SpinEvent.SPIN_FAST);
		}
	}
}
